<template>
  <el-upload
    ref="uploadRef"
    action="#"
    class="upload-res-file"
    :limit="props.limit"
    :accept="props.accept"
    :show-file-list="false"
    :before-upload="beforeUpload"
    :http-request="handleUploadFile"
  >
    <img class="plus" src="@/assets/png/icon_plus.png" alt="" />
  </el-upload>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import type { UploadProps, UploadRequestOptions } from 'element-plus';
import { uploadFile } from '@/api/common/';

interface Props {
  accept?: string;
  limit?: number;
  modelValue?: string;
  type: string;
  feature?: string;
}
const uploadRef = ref();
const props = withDefaults(defineProps<Props>(), {
  accept: '.jpg,.jpeg,.png,.bmp,.webp',
  limit: 1,
  feature: 'public',
});
const emits = defineEmits<{
  (e: 'update:modelValue', value: string): void;
  (e: 'success'): void;
}>();
const beforeUpload: UploadProps['beforeUpload'] = async (file) => {
  const fileSuffix = file.name.substring(file.name.lastIndexOf('.'));
  if (!props.accept?.includes(fileSuffix)) {
    ElMessage.warning('文件格式错误');
    return false;
  }
  if (file.size / 1024 / 1024 > 5) {
    ElMessage.warning('请上传小于5MB的图片');
    return false;
  }
};
const handleUploadFile = async (file: UploadRequestOptions) => {
  const formData = new FormData();
  formData.append('fileName', file.file);
  formData.append('name', file?.file?.name);
  formData.append('type', props.type);
  formData.append('feature', props.feature);
  const res = await uploadFile(formData);
  if (res && res.url) {
    ElMessage.success('上传成功');
    emits('success');
    uploadRef.value?.clearFiles();
  }
};
</script>

<style scoped></style>
